import Vue from 'vue'
import Router from 'vue-router'
import _ from 'lodash'

Vue.use(Router)

/* Layout */
import Layout from '@/layout'

import dashboardRouter from './modules/dashboard' // 首页
import departmentRouter from './modules/department' // 组织架构
import roleRouter from './modules/role' // 角色管理
import employeeRouter from './modules/employee' // 员工管理
import permissionRouter from './modules/permission' // 权限管理
import attendanceRouter from './modules/attendance' // 考勤管理
import approvalRouter from './modules/approval' // 审批管理
import salaryRouter from './modules/salary' // 工资管理
import socialRouter from './modules/social' // 社保管理

/**
 * Note: sub-menu only appear when route children.length >= 1
 * Detail see: https://panjiachen.github.io/vue-element-admin-site/guide/essentials/router-and-nav.html
 *
 * hidden: true                   if set true, item will not show in the sidebar(default is false)
 * alwaysShow: true               if set true, will always show the root menu
 *                                if not set alwaysShow, when item has more than one children route,
 *                                it will becomes nested mode, otherwise not show the root menu
 * redirect: noRedirect           if set noRedirect will no redirect in the breadcrumb
 * name:'router-name'             the name is used by <keep-alive> (must set!!!)
 * meta : {
    roles: ['admin','editor']    control the page roles (you can set multiple roles)
    title: 'title'               the name show in sidebar and breadcrumb (recommend set)
    icon: 'svg-name'/'el-icon-x' the icon show in the sidebar
    breadcrumb: false            if set false, the item will hidden in breadcrumb(default is true)
    activeMenu: '/example/list'  if set path, the sidebar will highlight the path you set
  }
 */

/**
 * constantRoutes
 * a base page that does not have permission requirements
 * all roles can be accessed
 */
// 静态路由
export const constantRoutes = [
  {
    path: '/login',
    name: 'login',
    component: () => import('@/views/login/index'),
    hidden: true
  },

  {
    path: '/404',
    name: '404',
    component: () => import('@/views/404'),
    hidden: true
  },

  {
    path: '/',
    name: 'layout',
    component: Layout,
    redirect: '/dashboard',
    children: [
      dashboardRouter // 首页
    ]
  }

  // 404 page must be placed at the end !!!
  // { path: '*', redirect: '/404', hidden: true }
]

// 动态路由
export const asyncRoutes = [
  departmentRouter, // 组织架构
  roleRouter, // 角色管理
  employeeRouter, // 员工管理
  permissionRouter, // 权限管理
  attendanceRouter, // 考勤管理
  approvalRouter, // 审批管理
  salaryRouter, // 工资管理
  socialRouter // 社保管理
]

const createRouter = () => new Router({
  mode: 'history', // require service support
  scrollBehavior: () => ({ y: 0 }),
  // 深拷贝constantRoutes，因为重置路由时还需要用到constantRoutes，深拷贝以避免污染
  routes: _.cloneDeep(constantRoutes)
})

const router = createRouter()

// Detail see: https://github.com/vuejs/vue-router/issues/1234#issuecomment-357941465
export function resetRouter() {
  const newRouter = createRouter()
  router.matcher = newRouter.matcher // reset router
  router.options.routes = newRouter.options.routes
}

/**
 * 为现有一级路由添加子路由
 *
 * @param {string} name 目标路由名称
 * @param {Array} childrenArr 子路由数组
 */
export function addChildrenRoutes(name, childrenArr) {
  // 遍历路由数组，找到目标路由
  const targetRoute = router.options.routes.find(item => item.name === name)
  // 如果找不到目标路由，打印错误消息
  if (!targetRoute) {
    console.error(`未找到名为${name}的一级路由`)
  }
  // 如果目标路由没有子路由，创建一个空的子路由数组
  if (!targetRoute.children) {
    targetRoute.children = []
  }
  // 将子路由数组添加到目标路由的children属性中
  targetRoute.children.push(...childrenArr)
  // 重新添加路由，以更新路由表
  router.addRoutes([targetRoute, { path: '*', redirect: '/404', hidden: true }])
  // 手动添加404页面到router.options.routes
  router.options.routes.push({ path: '*', redirect: '/404', hidden: true })
}

export default router
